package com.patui.widget;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class RoundThumb extends View{
	public RoundThumb(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public RoundThumb(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public RoundThumb(Context context) {
		super(context);
	}
	
	protected Bitmap mBitmap = null;
	
	public void setImageBitmap(Bitmap bitmap)
	{
		mBitmap = bitmap;
		invalidate();
	}
	
	public void setImageBitmap(int resId)
	{
		setImageBitmap(BitmapFactory.decodeResource(getResources(), resId));
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
		int sw = getWidth();
		int sh = getHeight();
		Paint paint = new Paint();
		paint.setColor(0xff9d9d9d);
		paint.setStyle(Style.FILL);
		canvas.drawRoundRect(new RectF(0, 0, sw, sh), 10.0f, 10.0f, paint);
		if(mBitmap != null)
		{
			float scale = (float)sw/mBitmap.getWidth();
			if(sw*scale < sh)
			{
				scale = (float)sh/mBitmap.getHeight();
			}
			int tempW = (int)Math.ceil(sw/scale);
			int tempH = (int)Math.ceil(sh/scale);
			if(tempW < 0) tempW = 0;
			if(tempW > mBitmap.getWidth()) tempW = mBitmap.getWidth();
			if(tempH < 0) tempH = 0;
			if(tempH > mBitmap.getHeight()) tempH = mBitmap.getHeight();
			Matrix m = new Matrix();
			m.postScale(scale, scale);
			Bitmap tempBmp = Bitmap.createBitmap(mBitmap, mBitmap.getWidth()-tempW, mBitmap.getHeight()-tempH, tempW, tempH, m, true);
			Path path = new Path();
			path.addRoundRect(new RectF(1, 1, sw-1, sh-1), 10, 10, Path.Direction.CW);
			BitmapShader tempShader = new BitmapShader(tempBmp,BitmapShader.TileMode.CLAMP,BitmapShader.TileMode.CLAMP);
			paint.setShader(tempShader);
			canvas.drawPath(path, paint);
		}
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(60,60);
	}
}
